package com.dms.modules.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dms.common.exception.BusinessException;
import com.dms.modules.product.dto.ProductSpecDTO;
import com.dms.modules.product.entity.ProductSpec;
import com.dms.modules.product.mapper.ProductSpecMapper;
import com.dms.modules.product.service.ProductSpecService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProductSpecServiceImpl extends ServiceImpl<ProductSpecMapper, ProductSpec> implements ProductSpecService {

    private final ObjectMapper objectMapper;

    public ProductSpecServiceImpl(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean create(ProductSpecDTO specDTO) {
        try {
            ProductSpec spec = new ProductSpec();
            BeanUtils.copyProperties(specDTO, spec);
            
            // 将规格值列表转换为JSON字符串
            if (specDTO.getValues() != null) {
                spec.setValues(objectMapper.writeValueAsString(specDTO.getValues()));
            }
            
            return save(spec);
        } catch (Exception e) {
            log.error("创建规格失败", e);
            throw new BusinessException("创建规格失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(ProductSpecDTO specDTO) {
        try {
            ProductSpec spec = super.getById(specDTO.getId());
            if (spec == null) {
                throw new BusinessException("规格不存在");
            }
            
            BeanUtils.copyProperties(specDTO, spec);
            
            // 将规格值列表转换为JSON字符串
            if (specDTO.getValues() != null) {
                spec.setValues(objectMapper.writeValueAsString(specDTO.getValues()));
            }
            
            return updateById(spec);
        } catch (Exception e) {
            log.error("更新规格失败", e);
            throw new BusinessException("更新规格失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        try {
            return removeById(id);
        } catch (Exception e) {
            log.error("删除规格失败", e);
            throw new BusinessException("删除规格失败：" + e.getMessage());
        }
    }

    @Override
    public ProductSpecDTO getSpecById(Long id) {
        try {
            ProductSpec spec = super.getById(id);
            if (spec == null) {
                return null;
            }
            
            ProductSpecDTO specDTO = new ProductSpecDTO();
            BeanUtils.copyProperties(spec, specDTO);
            
            // 将JSON字符串转换为规格值列表
            if (StringUtils.hasText(spec.getValues())) {
                try {
                    specDTO.setValues(objectMapper.readValue(spec.getValues(), List.class));
                } catch (JsonProcessingException e) {
                    log.error("解析规格值失败", e);
                }
            }
            
            return specDTO;
        } catch (Exception e) {
            log.error("获取规格详情失败", e);
            throw new BusinessException("获取规格详情失败：" + e.getMessage());
        }
    }

    @Override
    public List<ProductSpecDTO> listSpecs() {
        try {
            List<ProductSpec> specs = list(new LambdaQueryWrapper<ProductSpec>()
                    .eq(ProductSpec::getDeleted, 0)
                    .orderByAsc(ProductSpec::getSort));
            
            return specs.stream().map(spec -> {
                ProductSpecDTO specDTO = new ProductSpecDTO();
                BeanUtils.copyProperties(spec, specDTO);
                
                // 将JSON字符串转换为规格值列表
                if (StringUtils.hasText(spec.getValues())) {
                    try {
                        specDTO.setValues(objectMapper.readValue(spec.getValues(), List.class));
                    } catch (JsonProcessingException e) {
                        log.error("解析规格值失败", e);
                    }
                }
                
                return specDTO;
            }).collect(Collectors.toList());
        } catch (Exception e) {
            log.error("获取规格列表失败", e);
            throw new BusinessException("获取规格列表失败：" + e.getMessage());
        }
    }

    @Override
    public List<ProductSpecDTO> getByCategoryId(Long categoryId) {
        try {
            List<ProductSpec> specs = list(new LambdaQueryWrapper<ProductSpec>()
                    .eq(ProductSpec::getCategoryId, categoryId)
                    .eq(ProductSpec::getDeleted, 0)
                    .orderByAsc(ProductSpec::getSort));
            
            return specs.stream().map(spec -> {
                ProductSpecDTO specDTO = new ProductSpecDTO();
                BeanUtils.copyProperties(spec, specDTO);
                
                // 将JSON字符串转换为规格值列表
                if (StringUtils.hasText(spec.getValues())) {
                    try {
                        specDTO.setValues(objectMapper.readValue(spec.getValues(), List.class));
                    } catch (JsonProcessingException e) {
                        log.error("解析规格值失败", e);
                    }
                }
                
                return specDTO;
            }).collect(Collectors.toList());
        } catch (Exception e) {
            log.error("获取分类规格列表失败", e);
            throw new BusinessException("获取分类规格列表失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchCreate(List<ProductSpecDTO> specDTOs) {
        try {
            List<ProductSpec> specs = specDTOs.stream().map(specDTO -> {
                ProductSpec spec = new ProductSpec();
                BeanUtils.copyProperties(specDTO, spec);
                
                // 将规格值列表转换为JSON字符串
                if (specDTO.getValues() != null) {
                    try {
                        spec.setValues(objectMapper.writeValueAsString(specDTO.getValues()));
                    } catch (JsonProcessingException e) {
                        log.error("转换规格值失败", e);
                    }
                }
                
                return spec;
            }).collect(Collectors.toList());
            
            return saveBatch(specs);
        } catch (Exception e) {
            log.error("批量创建规格失败", e);
            throw new BusinessException("批量创建规格失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchDelete(List<Long> ids) {
        try {
            return removeByIds(ids);
        } catch (Exception e) {
            log.error("批量删除规格失败", e);
            throw new BusinessException("批量删除规格失败：" + e.getMessage());
        }
    }
} 